(() => {
    const canvass = document.querySelector('.runner-canvas')
    const context = canvass.getContext("2d")
    const searchRangeX = {
        min: 69,
        max: 135,
    }
    const searchRangeY = {
        min: 93,
        max: 123
    }

    let timer = null

    const jump = () => {
        let event = new KeyboardEvent('keydown', { 'keyCode': 32, 'which': 32 })
        document.dispatchEvent(event)
    }

    const replay = () => {
        let event = new KeyboardEvent('keyup', { 'keyCode': 32, 'which': 32 })
        document.dispatchEvent(event)
        clearInterval(timer)
        searchRangeX.max = 135
    }

    const drawDebugRect = (x, y, w, h) => {
        context.rect(x, y, w, h)
        context.stroke()
    }

    const checkHasBarrier = () => {
        const x = searchRangeX.min
        const y = searchRangeY.min
        const w = searchRangeX.max - searchRangeX.min
        const h = searchRangeY.max - searchRangeY.min
        const imgData = context.getImageData(x, y, w, h)
        const d = imgData.data
        // drawDebugRect(x, y, w, h)

        return [...new Set(d)].length !== 1
    }

    const step = () => {
        let isBarrier = checkHasBarrier()
        if (isBarrier) {
            jump()
        }
        requestAnimationFrame(step)
    }

    const increaseBox = () => {
        timer = setInterval(() => {
            if (searchRangeX.max < 220) {
                searchRangeX.max += 1
            }
        }, 3.5 * 1000)
    }

    const main = () => {
        jump()
        step()
        increaseBox()
    }


    main()

})()
